<?php

namespace app\admin\controller\auth;

use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;

use app\common\library\FSHelper;
use think\Db;
use think\Log;

/**
 * 管理员管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Admin extends Backend
{

    protected $model = null;
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];

    //protected $dataLimit = 'auth';

    protected $searchFields = 'username';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');

        $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(true);

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin())
        {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v)
            {
                $groupdata[$v['id']] = $v['name'];
            }
        }
        else
        {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n)
            {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v)
                {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }

        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
    }

    /**
     * 查看
     */
    public function index()
    {

        //当前是否为关联查询
        $this->relationSearch = true;
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $childrenGroupIds = $this->childrenGroupIds;
            $groupName = AuthGroup::where('id', 'in', $childrenGroupIds)
                    ->column('id,name');
            $authGroupList = AuthGroupAccess::where('group_id', 'in', $childrenGroupIds)
                    ->field('uid,group_id')
                    ->select();


            $agentCheck = Db::name('admin')
                ->where('id',$this->auth->id)
                ->find();
            //如果是代理
            if($agentCheck['level'] && $this->auth->id !=1){

                //如果是其他代理账户 递归查询所有下级子账户
                $arr = [];
                $list = self::children($this->auth->id,$arr);

                array_push($list,$this->auth->id);
                $this->childrenAdminIds = $list;


            }


            $adminGroupName = [];
            foreach ($authGroupList as $k => $v)
            {
                if (isset($groupName[$v['group_id']]))
                    $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
            }
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n)
            {
                $adminGroupName[$this->auth->id][$n['id']] = $n['name'];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = (array)json_decode($this->request->get('filter'));
            if(isset($filter['groups_text']))
            {

                $ids = Db::name('admin')
                    ->alias('a')
                    ->join('auth_group_access g','g.uid = a.id','left')
                    ->join('auth_group j','j.id = g.group_id','left')
                    ->where('j.name',$filter['groups_text'])
                    ->field('a.id')
                    ->select();
                $this->childrenAdminIds = [];
                foreach ($ids as $value)
                {
                    $this->childrenAdminIds[] = $value['id'];
                }
                $where = [];
                foreach ($filter as $key =>$val)
                {
                    if($key=='groups_text')
                    {
                        unset($key);
                    }else{
                        $where[$key] = ['=',$val];
                    }
                }
            }
            $total = $this->model
		    ->with('admin')
                    ->where($where)
                    ->where('id', 'in', $this->childrenAdminIds)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
		    ->with('admin')
                    ->where($where)
                    ->where('id', 'in', $this->childrenAdminIds)
                    ->field(['password', 'salt', 'token'], true)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $k => &$v)
            {
		$relation = $v->getRelation('admin');
		if ($relation) {
			$relation->visible(['nickname']);
		}
		//$v->getRelation('admin')->visible(['nickname']);
                $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
                $v['groups'] = implode(',', array_keys($groups));
                $v['groups_text'] = implode(',', array_values($groups));
                $lineArr = Db::name('gateway')
                    ->where('admin_id',$v['id'])
                    ->field('name')
                    ->select();
                $line = '';
                foreach ($lineArr as $value)
                {
                    $line .=$value['name'].',';
                }
                $v['line'] = $line;
            }
            unset($v);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /*
     * 添加个人账号前检索公司帐号
     */
    public function company()
    {
        $data = Db::name('admin')
            ->where('id',$this->auth->id)
            ->field('id,username,auth_number')
            ->select();
        if(!$data)
        {
            return json(['code'=>0,'msg'=>'创建个人账号前必须先创建公司帐号']);
        }

        return json($data);

    }

    /**
     * @param $code
     * @param $list
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 递归查询当前代理下的所有帐号
     */
    public static function children($code,&$list)
    {
        $children = Db::name('admin')
            ->where('pid',$code)
            ->field('id')
            ->select();

        if($children)
        {
            foreach ($children as $value)
            {
                array_push($list,$value['id']);
                self::children($value['id'],$list);
            }
        }
        
        return $list;
    }

    public function checkLevel($groupName)
    {
        if($groupName == '一级代理')
        {
            $level=1;
        }elseif ($groupName == '二级代理')
        {
            $level=2;
        }elseif ($groupName == '公司账号')
        {
            $level=3;
        }else
        {
            $level=4;
        }
        return $level;
    }

    /**
     * 添加
     */
    public function add()
    {

        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
                $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                
                $params['nickname'] = $params['username'];
                unset($params['email']);

                $group = $this->request->post("group/a");
                if (in_array('3', $group)) {
                    if (empty($params['admin_id'])) {
                        $this->error(__('请选择坐席所属门店组长'));
                    }
                } else {
                    unset($params['admin_id']);
                }

                if($params['telephone'])
                {
                    if (!preg_match("/^1[345678]{1}\d{9}$/", $params['telephone']))
                    {
                        $this->error(__('联系方式号码错误'));
                    }
                }

                //如果是代理，分配线路
                if($this->request->has('agent'))
                {

                    //判断当前帐号是否为代理并且有操作权限
                    $validate = Db::name('auth_group_access')
                        ->alias('a')
                        ->join('auth_group g','g.id = a.group_id')
                        ->where('a.uid',$this->auth->id)
                        ->value('g.agent');

                    if(!$validate){
                        $this->error('您不是代理，请勿勾选');
                    }

                    /**
                     * 代理组，取出组名分级，存入admin表为了后期取数据做扩展
                     */
                    $groupName = Db::name('auth_group')
                        ->where('id',$group[0])
                        ->value('name');

                    $level = $this->checkLevel($groupName);

                    $params['level']    = $level;
                    
                    $params['pid'] = $this->auth->id;

                    $auth_number = Db::name('admin')
                        ->where('id',$this->auth->id)
                        ->value('auth_number');

                    if(!$auth_number)
                    {
                        $this->error('您的帐号数量已经不足');
                    }

                    if($level==4)
                    {
                         Db::name('admin')
                            ->where('id',$this->auth->id)
                            ->setDec('auth_number');
                         Db::name('admin')
                            ->where('id',$this->auth->id)
                            ->setInc('used_count');
                        Log::info('【代理管理】'.date('Y-m-d H:i:s').$this->auth->id.'创建了'.$level.'级帐号'.$params['username'].'消耗了1根线路');
                    }else{
                        if($params['auth_number']>$auth_number){
                            $this->error('您的线路不够');
                        }
                        //更新分配者线路的数量
                        Db::name('admin')
                            ->where('id',$this->auth->id)
                            ->update(['auth_number'=>$auth_number-$params['auth_number']]);

                        Log::info('【代理管理】'.date('Y-m-d H:i:s').$this->auth->id.'创建了'.$level.'级帐号'.$params['username'].'并非配了'.$params['auth_number'].'根线路');
                    }


                }

                $result = $this->model->validate('Admin.add')->save($params);
                if ($result === false)
                {
                    $this->error($this->model->getError());
                }
                //$group = $this->request->post("group/a");

                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                $dataset = [];
                foreach ($group as $value)
                {
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                if ($params['password'])
                {
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                }
                else
                {
                    unset($params['password'], $params['salt']);
                }
                
                if($params['telephone'])
                {
                    if (!preg_match("/^1[345678]{1}\d{9}$/", $params['telephone']))
                    {
                        $this->error(__('联系方式号码错误'));
                    }
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
                    'username' => 'require|max:50|unique:admin,username,' . $row->id,
                    'email'    => 'email|unique:admin,email,' . $row->id
                ]);
//var_dump($params);die();

                $group = $this->request->post("group/a");
                if (in_array('3', $group)) {
                    if (empty($params['admin_id'])) {
                        $this->error(__('请选择坐席所属门店组长'));
                    }
                } else {
                    unset($params['admin_id']);
                }

                $params['nickname'] = $params['username'];
                unset($params['email']);

                //如果是代理，分配线路
                if($this->request->has('agent')){
                    //判断当前帐号是否为代理并且有操作权限
                    $validate = Db::name('auth_group_access')
                        ->alias('a')
                        ->join('auth_group g','g.id = a.group_id')
                        ->where('a.uid',$this->auth->id)
                        ->value('g.agent');

                    if(!$validate){
                        $this->error('您不是代理，请勿勾选');
                    }

                    $auth_number = Db::name('admin')
                        ->where('id',$this->auth->id)
                        ->value('auth_number');

                    $auth_number_obj = Db::name('admin')
                        ->where('id',$ids)
                        ->value('auth_number');

                    if($params['auth_number']>$auth_number){
                        $this->error('您的线路不够');
                    }
                    
                    //更新分配者线路的数量
                    Db::name('admin')
                        ->where('id',$this->auth->id)
                        ->update(['auth_number'=>$auth_number-$params['auth_number']]);

                    $params['auth_number']+=$auth_number_obj;
                    Log::info('【代理管理】'.date('Y-m-d H:i:s').$this->auth->id.'编辑帐号'.$params['username'].'并非配了'.$params['auth_number'].'根线路');

                }

                $result = $row->validate('Admin.edit')->save($params);
                if ($result === false)
                {
                    $this->error($row->getError());
                }

                // 先移除所有权限
                model('AuthGroupAccess')->where('uid', $row->id)->delete();

                //$group = $this->request->post("group/a");

                // 过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);

                $dataset = [];
                foreach ($group as $value)
                {
                    $dataset[] = ['uid' => $row->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);

                $params['id'] = $row->id;

                $this->success();
            }
            $this->error();
        }
        $grouplist = $this->auth->getGroups($row['id']);
        $groupids = [];
        foreach ($grouplist as $k => $v)
        {
            $groupids[] = $v['id'];
        }
        $this->view->assign("row", $row);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenGroupIds;
            $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function($query) use($childrenGroupIds) {
                        $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
                    })->select();
            if ($adminList)
            {
                $deleteIds = [];
                foreach ($adminList as $k => $v)
                {
                    $deleteIds[] = $v->id;
                }
                $deleteIds = array_diff($deleteIds, [$this->auth->id]);
                if ($deleteIds)
                {
                    $this->model->destroy($deleteIds);
                    model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
                    $this->success();
                }
            }
        }
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * 下拉搜索
     */
    public function selectpage()
    {
        if (! $this->request->isPost()) {
            $this->error(__('You have no permission'));
        }
        $this->dataLimit = 'auth';
        $this->dataLimitField = 'id';

        //return parent::selectpage();

        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array) $this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr");
        //排序方式
        $orderby = (array) $this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array) $this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array) $this->request->request("custom/a");
        $order = [];
        foreach ($orderby as $k => $v)
        {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null)
        {
            $where = [$primarykey => ['in', $primaryvalue]];
        }
        else
        {
            $where = function($query) use($word, $andor, $field, $searchfield, $custom) {
                foreach ($word as $k => $v)
                {
                    foreach ($searchfield as $m => $n)
                    {
                        $query->where($n, "like", "%{$v}%", $andor);
                    }
                }
                if ($custom && is_array($custom))
                {
                    foreach ($custom as $k => $v)
                    {
                        $query->where($k, '=', $v);
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0)
        {
            if (is_array($adminIds))
            {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($where)
                    ->order($order)
                    ->page($page, $pagesize)
                    ->field("{$primarykey},{$field}")
                    ->field("password,salt", true)
                    ->select();
            $list = collection($list);
            foreach ($list as &$one) {
                unset($one['extension_password']);
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    /**
     * 下拉搜索2
     */
    public function selectpage2()
    {

        if (! $this->request->isPost()) {
            $this->error(__('You have no permission'));
        }

        $this->dataLimit = 'auth';
        $this->dataLimitField = 'id';
        //return parent::selectpage();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //当前是否为关联查询
        $this->relationSearch = true;

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array) $this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr");
        //排序方式
        $orderby = (array) $this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array) $this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array) $this->request->request("custom/a");
        $order = [];
        foreach ($orderby as $k => $v)
        {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null)
        {
            $where = [$primarykey => ['in', $primaryvalue]];
        }
        else
        {
            $where = function($query) use($word, $andor, $field, $searchfield, $custom) {
                foreach ($word as $k => $v)
                {
                    foreach ($searchfield as $m => $n)
                    {
                        $query->where($n, "like", "%{$v}%", $andor);
                    }
                }
                if ($custom && is_array($custom))
                {
                    foreach ($custom as $k => $v)
                    {
                        $query->where($k, '=', $v);
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
	    $this->model->with('auth_group_access')->where('group_id', '=', 2);
        $total = $this->model->where($where)->count();
        if ($total > 0)
        {
            if (is_array($adminIds))
            {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
	    $this->model->with('auth_group_access')->where('group_id', '=', 2);
            $list = $this->model->where($where)
                    ->order($order)
                    ->page($page, $pagesize)
                    ->field("{$primarykey},{$field}")
                    ->field("password,salt", true)
                    ->select();
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

}

